﻿using Aspose.Words;
using Aspose.Words.Drawing;
using Aspose.Words.Fields;
using CommTestNFW;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace AsposeWordTest
{
    public class AsposeWordHelper
    {
        public static string BasePath = "D:/test/";
        public void Build(string imagePath)
        {
             imagePath = imagePath ?? $"{BasePath}test-replace.jpg";
            //方法1  替换图片
            ReplaceDocx(imagePath);

            //方法2  读取html, 转换为word
            //loadHtml();

            //从图片创建word
            //create();
        }

        public void create()
        {
            Document doc = new Document();

            DocumentBuilder builder = new DocumentBuilder(doc);
            builder.InsertTextInput("test", TextFormFieldType.Regular, "", "tttttttttttttt", 100);
            builder.InsertParagraph();

            byte[] image = GetImage();
            builder.InsertImage(image);

            Shape shape = new Shape(doc, ShapeType.Rectangle);
            doc.BackgroundShape = shape;
            shape.ImageData.SetImage($"{BasePath}test.jpg");

            var size = shape.ImageData.ImageSize;
            shape.Width = size.WidthPixels + 100;
            shape.HorizontalAlignment = HorizontalAlignment.Right;
            shape.Height = size.HeightPixels + 1000;

            string path = $"{BasePath}test.docx";
            string path2 = $"{BasePath}test.pdf";
            doc.Save(path, SaveFormat.Docx);
            doc.Save(path2, SaveFormat.Pdf);

        }

        public void ReplaceDocx(string imagePath)
        {
            string docPath = $"{BasePath}test.docx";
            Document doc = new Document(docPath);

            Regex regex = new Regex("{*}");
            //doc.Range.Replace(regex, new ReplaceImage(""));

            var node = doc.FirstChild;

            var p = doc.FirstSection.Body.FirstParagraph;
            var shape = p.FirstChild as Shape;
            shape.ImageData.SetImage(imagePath);

            string path = $"{BasePath}testR.docx";
            string path2 = $"{BasePath}testR.pdf";
            doc.Save(path, SaveFormat.Docx);
            doc.Save(path2, SaveFormat.Pdf);
        }

        public void loadHtml()
        {
            string html = $"{BasePath}test.html";
            LoadOptions options = new LoadOptions();
            options.LoadFormat = LoadFormat.Html;
            Document doc = new Document(html);

            string path = $"{BasePath}testHtml.docx";
            string path2 = $"{BasePath}testHtml.pdf";
            doc.Save(path, SaveFormat.Docx);
            doc.Save(path2, SaveFormat.Pdf);
        }

        private byte[] GetImage()
        {
            string path = $"{BasePath}test.jpg";
            return File.ReadAllBytes(path);
        }
    }
}
